"""
客户信息相关：列表信息
"""

from django.shortcuts import render, HttpResponse, redirect
from sa import models
from django.http import JsonResponse
# 导入分页
from Utils.pagination import Pagination
from sa.forms.project_form import ProjectModelForm
from django.views.decorators.csrf import csrf_exempt


def customer_list(request):
    if request.method == 'GET':
        project_form = ProjectModelForm(request)

        # q有值，就拿value; 没值，就拿空字符串
        search_data = request.GET.get('q', '')
        if search_data:
            from django.db.models import Q
            # Q查询  |：或; &:与； ~：非
            queryset = (
                models.Customers.objects.exclude(status='1').
                filter(Q(name__contains=search_data) | Q(notes__contains=search_data))
                .order_by('-id')
            )
            page_object = Pagination(request, queryset)

            context = {
                'queryset': page_object.page_queryset,
                'count': queryset.count(),
                'page_string': page_object.html(),
                'search_data': search_data,
                'form': project_form,
            }

            return render(request, 'customer_list.html', context=context)
        else:
            # 处理空搜索数据的情况，例如返回所有客户
            queryset = models.Customers.objects.exclude(status='1').order_by('-id')
            page_object = Pagination(request, queryset)
            context = {
                'queryset': page_object.page_queryset,
                'count': queryset.count(),
                'page_string': page_object.html(),
                'search_data': '',
                'form': project_form,
            }
            return render(request, 'customer_list.html', context=context)


def customer_detail(request, c_id):
    """ 查看客户别名或备注 """
    row_dict = models.Customers.objects.filter(id=c_id).values('notes').first()
    if row_dict:
        return JsonResponse({'status': True, 'info': row_dict})
    else:
        return JsonResponse({'status': False, 'error': '不存在'})


@csrf_exempt
def add_project(request):
    if request.method == 'POST':
        project_form = ProjectModelForm(request, data=request.POST)
        customer_id = request.POST.get('customer_id', '')
        customer_obj = models.Customers.objects.filter(id=customer_id).first()
        print(f'对 {customer_obj} 创建项目！')
        if project_form.is_valid():
            instance = project_form.save(commit=False)
            instance.sa = request.sa
            instance.customer = customer_obj
            instance.save()
            # ManyToMany 必须项目对象存在,所以在save()后追加
            # 将登录用户追加到默认值
            instance.actors.add(request.sa)
            # 从 cleaned_data 中获取 actors 并添加到实例中
            # 假设 project_form 已经包含了正确的 actors 字段，并且前端发送了正确的数据
            actors_to_add = project_form.cleaned_data.get('actors', [])
            for actor in actors_to_add:
                instance.actors.add(actor)
            return JsonResponse({'status': True, 'info': '项目添加成功啦~~'})
        return JsonResponse({'status': False, 'error': project_form.errors})





